package logic

import (
	"context"
	"fmt"
	"vipshop/model/cache"
	"vipshop/model/mysql"
	"vipshop/pkg"
	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *vipshoprpc.ForgetPasswordRequest) (*vipshoprpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var m mysql.User
	mysql.Db.Debug().Where("account=?", in.Account).Find(&m)
	if m.ID == 0 {
		return nil, fmt.Errorf("账号未存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sengsms"+in.Account).Result()
	if in.Sengsms != result {
		return nil, fmt.Errorf("短信验证码输入错误")
	}
	s, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.Captcha != s {
		return nil, fmt.Errorf("图形验证码输入错误")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码输入不一致")
	}
	if m.Password == pkg.Md5(in.Password) {
		return nil, fmt.Errorf("新密码不能和原密码相同")
	}
	m.Password = pkg.Md5(in.Password)

	mysql.Db.Debug().Updates(&m)

	return &vipshoprpc.ForgetPasswordResponse{
		UserId: int64(m.ID),
	}, nil
}
